package com.ffcs.crmd.tsp.server.netty.client;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ffcs.crmd.tsp.api.netty.INettyChannelEventListener;
import com.ffcs.crmd.tsp.common.constant.LoggerName;
import com.ffcs.crmd.tsp.core.thread.ThreadFactoryImpl;
import com.ffcs.crmd.tsp.server.application.ApplicationManagerHolder;
import com.ffcs.crmd.tsp.server.manager.ClientRemotingManager;

import io.netty.channel.Channel;

/**
 * 
 * 功能说明:定期检测客户端连接，清除不活动的连接
 *
 * @author ZHONGFUHUA
 * 
 * @since 1.0.0-SNAPSHOT
 *
 */
public class ClientKeepActiveListener implements INettyChannelEventListener {
    
    /**
     * 日志
     */
    private final static Logger      log                      = LoggerFactory.getLogger(LoggerName.RemotingLoggerName);
    
    /**
     * 定时任务服务
     */
    private ScheduledExecutorService scheduledExecutorService = Executors
        .newSingleThreadScheduledExecutor(new ThreadFactoryImpl("TspClientKeepActiveScheduledThread"));
    /**
     * 定时扫描接入通道是否存活
     */
    private static final long        scanInActiveChannelTime  = 30 * 1000;
    
    /**
     * 客户端管理器
     */
    private ClientRemotingManager    clientRemotingManager    = ApplicationManagerHolder.getBean("clientRemotingManager",
        ClientRemotingManager.class);
    
    @Override
    public void start() {
        // 扫描失效的通道
        this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    ClientKeepActiveListener.this.clientRemotingManager.scanChannelTimeout();
                } catch (Exception e) {
                    log.error("NETTY SERVER CLIENT: scan inactive channel - but scheduled run exception:", e);
                }
            }
        }, 1000 * 10, scanInActiveChannelTime, TimeUnit.MILLISECONDS);
    }
    
    @Override
    public void shutdown() {
        this.scheduledExecutorService.shutdown();
    }
    
    @Override
    public void onChannelConnect(String remoteAddr, Channel channel) {
        
    }
    
    @Override
    public void onChannelClose(String remoteAddr, Channel channel) {
        this.clientRemotingManager.channelCloseEvent(channel);
        
    }
    
    @Override
    public void onChannelException(String remoteAddr, Channel channel) {
        //this.clientRemotingManager.channelCloseEvent(channel);
        
    }
    
    @Override
    public void onChannelIdle(String remoteAddr, Channel channel) {
       //this.clientRemotingManager.channelCloseEvent(channel);
        
    }
    
}
